//
//  LCNewClassViewController.swift
//  mggz
//
//  Created by QinWei on 2018/1/17.
//  Copyright © 2018年 爱丽丝的梦境. All rights reserved.
//

import UIKit
import Moya
import ObjectMapper
class LCNewClassViewController: UIViewController {

    @IBOutlet weak var projectName: UILabel!
    
    @IBOutlet weak var className: UITextField!
    
    @IBOutlet weak var decribleText: UITextField!
    
    @IBOutlet weak var timeLabel: UILabel!
    var timeSelectStr:String?
    var timeAlert:TWLAlertView?
    
    var timeSelectModel :LCAtteendceTimeModel? = nil
    var newClassSuccess:((Bool) -> Void)? = nil
    var currentProject: LCProjectListModel? {
        willSet {
            self.currentProject = newValue
        }
    }
    @IBOutlet weak var classLeader: UILabel!
    var guid:String?
    lazy var attendceTimeArray : [LCAtteendceTimeModel] = [LCAtteendceTimeModel]()
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = UIColor.init(red: 233/255.0, green: 233/255.0, blue: 233/255.0, alpha: 1)
        self.navigationItem.title = "未命名班组"
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "保存", fontSize: 17, self, #selector(saveData))
        self.setupGetUdid()
        self.projectName.text = ProjectName
        //self.setupAttendceTime()
        
    }
    
    @objc fileprivate func saveData(){
        let gutyy = "第一班组的"
        print(gutyy.count)
        guard let classNameCount1 = self.className.text, classNameCount1.count > 0 else {
            WWError("班组名为空")
            return
        }
        guard let classNameCount2 = self.className.text, classNameCount2.count < 6 else {
            WWError("班组名字数超限")
            return
        }
        
        guard let decribleCount2 = self.decribleText.text, decribleCount2.count < 11 else {
            WWError("描述字数超限")
            return
        }
        let jsonDic = [
            "ID": self.guid!,//同OrderId
            "Form": [
                "WorkGroupName": classNameCount1,//班组名称
                "Notes": decribleCount2,//描述
                "Order":1,//排序
                "WorkTimeQuantum": [
                    "ID": self.timeSelectModel?.ID//时间段
                ],
                "WorkGroupNumber": 0,//成员数量
                "WorkGroupHeadman": nil,//组长
                "ConstructionProject": [
                    "ID": self.currentProject?.MarketSupplyBaseID //项目MarketSupplyBaseID
                ]
            ],
            "BanZuChengYuan": [] //班组成员，固定空
            ] as [String : Any]
        let classJsonStr : String = self.getJSONStringFromDictionary(dictionary: jsonDic as NSDictionary)
        print(classJsonStr)
        print(self.guid as Any)
        
        guard let accountId = WWUser.sharedInstance.accountId else{
            return
        }
        print(accountId)
        LCAPiMainManager.request(.NewClassBody(orderId:self.guid!, jsonData:classJsonStr, AccountId: accountId, operate: "1")) { (result) in
            if case let .success(response) = result {
                guard  let jsonString :NSDictionary = try?response.mapJSON() as! NSDictionary else{
                    return
                }
                guard (jsonString["State"]) as! String == "OK" else{
                    return
                }
            self.newClassSuccess!(true)
            self.navigationController?.popViewController(animated: true)
            }
        }
        
}
    
    
   fileprivate func getJSONStringFromDictionary(dictionary:NSDictionary) -> String {
        if (!JSONSerialization.isValidJSONObject(dictionary)) {
            print("无法解析出JSONString")
            return ""
        }
        let data : NSData! = try? JSONSerialization.data(withJSONObject: dictionary, options: []) as NSData!
        let JSONString = NSString(data:data as Data,encoding: String.Encoding.utf8.rawValue)
        return JSONString! as String
        
    }
    @IBAction func timeSelectClick(_ sender: Any) {
        
        self.timeAlert = TWLAlertView.init(frame: CGRect(x: 0, y: 0, width: SCREEN_WIDTH, height: SCREEN_HEIGHT))
        var customHeight:CGFloat = 0
        var maxItem = 5
        if self.attendceTimeArray.count > maxItem{//43
            customHeight = CGFloat(maxItem) * CGFloat(43)
        }else{
            customHeight = CGFloat(self.attendceTimeArray.count) * CGFloat(43)
        }
        customHeight += CGFloat(70)
        let custom : LCTimeSelectPopView = LCTimeSelectPopView.init(frame: CGRect(x: 0, y: 0, width: 300, height: customHeight))
        custom.timeArray = self.attendceTimeArray
        custom.cancelButton.addTarget(self, action: #selector(alertCancel), for: .touchUpInside)
        custom.sureButton.addTarget(self, action: #selector(alertMakeSure), for: .touchUpInside)
        custom.pushNewButton.addTarget(self, action: #selector(managerTime(_:)), for: .touchUpInside)
        custom.timeSelectSuccess = {(value : LCAtteendceTimeModel,selectTitle:String) in
            self.timeSelectModel = value
            self.timeSelectStr = selectTitle
        }
        self.timeAlert?.initWithCustomView(custom, frame: CGRect(x: 0, y: 0, width: 300, height: customHeight))
        let keyWindow = UIApplication.shared.keyWindow
        keyWindow?.addSubview(self.timeAlert!)
    }
    @objc fileprivate func alertCancel(){
        self.timeAlert?.cancleView()
    }
    @objc fileprivate func alertMakeSure(){
        if self.timeSelectModel != nil{
            self.timeLabel.text = self.timeSelectStr
            self.timeAlert?.cancleView()
        }
    }
    @objc func managerTime(_ sender:UIButton){
        self.timeAlert?.cancleView()
        DispatchQueue.main.asyncAfter(deadline: DispatchTime.now()+0.4) {
            let timeInterval = TimeIntervalManagerViewController(nibName: "TimeIntervalManagerViewController", bundle: nil)
            self.navigationController?.pushViewController(timeInterval, animated: true)
        }
    }
    
    override func viewWillAppear(_ animated: Bool) {
        self.setupAttendceTime()
    }
    
    
    fileprivate func setupGetUdid(){
        guard let accountId = WWUser.sharedInstance.accountId else{
            return
        }
        LCAPiMainManager.request(.GETLCNewGuid(number: 1, AccountId: accountId)) { (result) in
            if case let .success(response) = result {
                guard  let jsonString :NSDictionary = try?response.mapJSON() as! NSDictionary else{
                    return
                }
                guard (jsonString["Status"]) as! String == "OK" else{
                    return
                }
                self.guid = (jsonString["Guid"] as! String)
            }
        }
        
    }
    
    fileprivate func setupAttendceTime(){
        QWTextWithStatusHud("数据正在载入...", target: self.view)
        guard let accountId = WWUser.sharedInstance.accountId else{
            return
        }
        LCAPiMainManager.request(.GETAttendanceTime(start: 0, limit: 100, AccountId: accountId)) { (result) in
            QWHudDiss(self.view)
            if case let .success(response) = result {
                guard  let jsonString :NSDictionary = try?response.mapJSON() as! NSDictionary else{
                    
                    return
                }
                guard (jsonString["State"]) as! String == "OK" else{
                    return
                }
                guard let resultDic = jsonString["Result"] as? [String: AnyObject] else{
                    return
                }
                guard let itemsArray = resultDic["Items"] as? NSArray else{
                    return
                }
                self.attendceTimeArray = Mapper<LCAtteendceTimeModel>().mapArray(JSONObject: itemsArray)!
                guard self.attendceTimeArray.count>0 else{
                    return
                }
                
                if self.attendceTimeArray.count > 0{
                    self.timeSelectModel = self.attendceTimeArray[0]
                    
                    
                    
                    if self.timeSelectModel?.IsDefault == true{
                        let defaultstr = "默认时段 "
                        let startStr = self.timeSelectModel?.BeginTime?.getSubstring(11, end: 16)
                        let endStr = self.timeSelectModel?.EndTime?.getSubstring(11, end: 16)
                        if self.timeSelectModel?.IsLastDay == true{
                            let titleStr = defaultstr+startStr!+"—"+"第二天"+endStr!
                            self.timeLabel.text = titleStr
                        }else{
                            let titleStr = defaultstr+startStr!+"—"+endStr!
                            self.timeLabel.text = titleStr
                        }
                    }else{
                        let startStr = self.timeSelectModel?.BeginTime?.getSubstring(11, end: 16)
                        let endStr = self.timeSelectModel?.EndTime?.getSubstring(11, end: 16)
                        if self.timeSelectModel?.IsLastDay == true{
                            let titleStr = startStr!+"—"+"第二天" + endStr!
                            self.timeLabel.text = titleStr
                        }else{
                            let titleStr = startStr!+"—"+endStr!
                            self.timeLabel.text = titleStr
                        }
                    }
                }
                
                print(self.attendceTimeArray)
                print(jsonString)
            }
        }
        
    }
}
